const axios = require('axios');

/**
 * 测试完整流程增强版的authToken功能
 */
async function testCompleteFlowWithAuthToken() {
    console.log('=== 测试完整流程增强版的authToken功能 ===\n');

    const baseURL = 'http://localhost:3000';
    const testUrl = 'https://shop.tiktok.com/view/product/1731808168774042656?region=MY&local=en&source=product_detail';

    // 自定义authToken示例
    const customAuthToken = {
        "name": "13143359181",
        "expires": 1757322261597,
        "accessToken": "Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJ7XCJhY2NvdW50TnVtYmVyXCI6XCIxMzE0MzM1OTE4MVwiLFwiYWNjb3VudFR5cGVcIjowLFwiYXBwbHlTdGF0dXNcIjoyLFwiYnVzaW5lc3NUeXBlXCI6MixcImZyb21TeXN0ZW1cIjoxMyxcImlkXCI6NTQwMTUyLFwiaXNFeHBpcmVcIjpmYWxzZSxcImp3dElkXCI6XCI5NDRjMmM2NTdhNTQ0ODJkOWRkMzRkM2Q3YmI2ZDc4OFwiLFwibG9naW5OYW1lXCI6XCIxMzE0MzM1OTE4MVwiLFwibWVyY2hhbnRJZFwiOjUzMTU0OCxcInByb2ZpbGVcIjpcImdjcF91c193ZXN0MVwiLFwic3lzdGVtSWRcIjo4LFwidG9rZW5FeHBpcmVEYXRlXCI6MTc1NzMyMjI2MTQwNyxcIndlY2hhdFN1YlwiOmZhbHNlfSIsImlzcyI6Inp6LXNhYXMtcGVyaW1zc2lvbiIsImlhdCI6MTc1NjcxNzQ2MSwianRpIjoiOTQ0YzJjNjU3YTU0NDgyZDlkZDM0ZDNkN2JiNmQ3ODgifQ.AGhNKdNQfUi7FoxHBgiL33157ls6y8zUfmk-G585rX8",
        "userId": 540152,
        "phone": "13143359181",
        "locale": "en"
    };

    try {
        // 测试1：使用默认authToken
        console.log('📋 测试1：使用默认authToken的完整流程');
        console.log('发送请求...');

        const response1 = await axios.post(`${baseURL}/api/products/complete-flow-with-videos`, {
            url: testUrl
        });

        console.log('✅ 默认authToken测试成功');
        console.log('响应状态:', response1.status);
        console.log('响应数据:', JSON.stringify(response1.data, null, 2));
        console.log('\n' + '='.repeat(80) + '\n');

        // 等待一段时间避免请求过频
        console.log('⏳ 等待3秒后进行下一个测试...');
        await new Promise(resolve => setTimeout(resolve, 3000));

        // 测试2：使用自定义authToken
        console.log('📋 测试2：使用自定义authToken的完整流程');
        console.log('自定义authToken信息:');
        console.log('- 用户名:', customAuthToken.name);
        console.log('- 用户ID:', customAuthToken.userId);
        console.log('- 过期时间:', new Date(customAuthToken.expires).toLocaleString());
        console.log('发送请求...');

        const response2 = await axios.post(`${baseURL}/api/products/complete-flow-with-videos`, {
            url: testUrl,
            authToken: customAuthToken
        });

        console.log('✅ 自定义authToken测试成功');
        console.log('响应状态:', response2.status);
        console.log('响应数据:', JSON.stringify(response2.data, null, 2));

        // 比较两次结果
        console.log('\n' + '='.repeat(80));
        console.log('📊 结果对比分析');
        console.log('='.repeat(80));

        const data1 = response1.data.data;
        const data2 = response2.data.data;

        console.log('默认authToken结果:');
        console.log('- 商品ID:', data1.product?.id);
        console.log('- 商品名称:', data1.product?.productName);
        console.log('- 视频数量:', data1.videoData?.videoCount || 0);
        console.log('- 步骤完成情况:', data1.steps || response1.data.steps);

        console.log('\n自定义authToken结果:');
        console.log('- 商品ID:', data2.product?.id);
        console.log('- 商品名称:', data2.product?.productName);
        console.log('- 视频数量:', data2.videoData?.videoCount || 0);
        console.log('- 步骤完成情况:', data2.steps || response2.data.steps);

        console.log('\n🎉 所有测试完成！');

    } catch (error) {
        console.error('❌ 测试失败:', error.message);

        if (error.response) {
            console.error('响应状态:', error.response.status);
            console.error('响应数据:', JSON.stringify(error.response.data, null, 2));
        }

        console.error('错误详情:', error.stack);
    }
}

/**
 * 测试authToken过期场景
 */
async function testExpiredAuthToken() {
    console.log('\n=== 测试authToken过期场景 ===\n');

    const baseURL = 'http://localhost:3000';
    const testUrl = 'https://shop.tiktok.com/view/product/1731808168774042656?region=MY&local=en&source=product_detail';

    // 过期的authToken
    const expiredAuthToken = {
        "name": "test_user",
        "expires": 1000000000000, // 已过期的时间戳
        "accessToken": "Bearer expired_token",
        "userId": 123456,
        "phone": "12345678901",
        "locale": "en"
    };

    try {
        console.log('📋 测试过期authToken的处理');
        console.log('过期时间:', new Date(expiredAuthToken.expires).toLocaleString());
        console.log('发送请求...');

        const response = await axios.post(`${baseURL}/api/products/complete-flow-with-videos`, {
            url: testUrl,
            authToken: expiredAuthToken
        });

        console.log('响应状态:', response.status);
        console.log('响应数据:', JSON.stringify(response.data, null, 2));

    } catch (error) {
        console.log('✅ 正确捕获了过期token错误');
        console.log('错误信息:', error.response?.data?.message || error.message);

        if (error.response) {
            console.log('响应状态:', error.response.status);
            console.log('响应数据:', JSON.stringify(error.response.data, null, 2));
        }
    }
}

/**
 * 主函数
 */
async function main() {
    console.log('🚀 开始测试完整流程的authToken功能\n');

    try {
        // 测试正常场景
        await testCompleteFlowWithAuthToken();

        // 测试异常场景
        await testExpiredAuthToken();

        console.log('\n✅ 所有测试完成！');

    } catch (error) {
        console.error('\n❌ 测试过程中出现错误:', error.message);
    }
}

// 运行测试
if (require.main === module) {
    main();
}

module.exports = {
    testCompleteFlowWithAuthToken,
    testExpiredAuthToken
};